package lanou.autohome.my;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import lanou.autohome.R;
import lanou.autohome.SouSuoActivity;
import lanou.autohome.basetool.BaseFragment;
import lanou.autohome.basetool.MyApp;

/**
 * Created by dllo on 16/8/15.
 * 我的
 */
public class MeFragment extends BaseFragment implements View.OnClickListener{

    private RelativeLayout relativeLayout;
    private RelativeLayout rl;
    private View notEnterView;
    private View enterView;
    //退出当前账号
    private RelativeLayout exit;
    //用户头像
    private ImageView touxiang;
    //头像Bitmap
    private Bitmap head;
    //名字
    private TextView name;


    @Override
    protected int setLayout() {
        return R.layout.fragment_me;
    }

    @Override
    protected void initView() {
        //占位布局
        rl = bindVie(R.id.fragment_me_rl);
        //未登录的布局
        notEnterView = LayoutInflater.from(mcontext).inflate(R.layout.activity_notlogin_me , null);
        Button accountEnter = (Button) notEnterView.findViewById(R.id.btn_zhanghao_me);
        accountEnter.setOnClickListener(this);
        //登录的布局
        enterView = LayoutInflater.from(mcontext).inflate(R.layout.activity_loginsucceed_me , null);
        name  =  (TextView) enterView.findViewById(R.id.textview_name_loginsucceed_me);
        touxiang = (ImageView) enterView.findViewById(R.id.imageview_touxiang_loginsucceed_me);
        touxiang.setOnClickListener(this);
        //退出登录
        exit = (RelativeLayout) enterView.findViewById(R.id.relativelayout_tuichu_loginsucceed_me);
        exit.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        set();
    }
    public void set(){
        MyBemoUser myBemoUser = BmobUser.getCurrentUser(MyBemoUser.class);
        if (myBemoUser != null){
            name.setText(myBemoUser.getUsername());
            if (myBemoUser.getIcon() == null) {
                touxiang.setImageResource(R.mipmap.ic_launcher);
            } else {
                touxiang.setImageBitmap(myBemoUser.getIcon());
            }
            rl.removeAllViews();
            rl.addView(enterView);
        } else {
            rl.removeAllViews();
            rl.addView(notEnterView);
        }
    }
    @Override
    protected void intiData() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_zhanghao_me:
                Intent zhanghao = new Intent(getContext(), LoginActivity.class);
                getActivity().startActivityForResult(zhanghao , 1);
                break;
            case R.id.relativelayout_tuichu_loginsucceed_me:
                BmobUser.logOut();//清除缓存用户对象
                BmobUser currentUser = BmobUser.getCurrentUser();//现在的currentuser是空的了

                FragmentManager fragmentManager =getFragmentManager();
                //创建修改实例
                MeFragment fragment = new MeFragment();
                FragmentTransaction transaction =getFragmentManager().beginTransaction();

                transaction.replace(R.id.activity_group_framelayout,fragment);
                transaction.addToBackStack(null);
                transaction.commit();
                break;
            case R.id.imageview_touxiang_loginsucceed_me:
                showTypeDialog();
                break;
        }
    }

    private void showTypeDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        final AlertDialog dialog = builder.create();
        View view = View.inflate(getContext(), R.layout.item_dialog_loginsucceed_me, null);
        TextView xiangji = (TextView) view.findViewById(R.id.textview_xiangji_dialog_loginsucceed_me);
        TextView xiangce= (TextView) view.findViewById(R.id.textview_xiangce_dialog_loginsucceed_me);
        // 在相册中选取
        xiangce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, 1);
                dialog.dismiss();
            }
        });
        // 调用照相机
        xiangji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent2.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));
                startActivityForResult(intent2, 2);// 采用ForResult打开
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("MeFragment", "resultCode:" + resultCode);
        if(resultCode == -1) {
            switch (requestCode) {
                case 1:
                    cropPhoto(data.getData());// 裁剪图片
                    break;
                case 2:
                    File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                    cropPhoto(Uri.fromFile(temp));// 裁剪图片
                    break;
                case 3:
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");

                    MyBemoUser user = BmobUser.getCurrentUser(MyBemoUser.class);
                    if (user != null) {
                        user.setIcon(head);
                        user.update(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                    Toast.makeText(mcontext, "更新成功", Toast.LENGTH_SHORT).show();
                                    touxiang.setImageBitmap(head);
                                } else {
                                    Toast.makeText(mcontext, "上传失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 调用系统的裁剪功能
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }
}
